/**
 * 策略：ma5上穿ma10指数，附加条件：macd 三日递增
 */
create or replace function getstma5(days int) returns setof record as
$$
declare
rec record;
begin
  for rec in EXECUTE '
	select b."date",b.macd,b.code,b."close"*0.99 as "mrj",s."name",s.industry from basic_data b left join stocks s  on b.code=s.code 
	where b.ma5 >= b.ma10
	--and b.high> ma20 
	--and b.low < ma20
	and strpos(s."name",''ST'')=0
	and to_date(b.date,''YYYY-MM-DD'') = getwd(current_date,'||days||')
	and volume < vol5*1.8  -- volume >= vol5 -- and
	and macd::float8 >-0.1
	and b."close"*b.volume>200000 --交易量大于一千万
	and s."timeToMarket" <>0 and to_date(to_char(s."timeToMarket",''99999999''),''YYYYMMDD'') < current_date-180
	and (select ma5 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+1||') and code=b.code) <= (select ma10 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+1||') and code=b.code) 	
	and (select ma5 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+2||') and code=b.code) < (select ma10 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+2||') and code=b.code) 
	and (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+1||') and code=b.code) > (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+2||') and code=b.code)
	and (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+2||') and code=b.code) > (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+3||') and code=b.code)
	and (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+3||') and code=b.code) > (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+4||') and code=b.code)
	and (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+4||') and code=b.code) <0
	--前面14日macd均值过小的
	and (select (avg(macd::float8)) from basic_data where  to_date(date,''YYYY-MM-DD'') <= getwd(current_date,'||days||') and to_date(date,''YYYY-MM-DD'') >= getwd(current_date,'||days+14||')  and code=b.code) <= -0.1
	order by macd::float8;
' loop
    return next rec;
  end loop;
return;
end
$$
language 'plpgsql';